package com.atguigu.json;

import com.atguigu.pojo.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTest {

    //1.2.1 javaBean和json的转换
    @Test
    public void test1(){
        Person person=new Person(1,"国哥很帅");
        //创建Gson对象实例
        Gson gson=new Gson();

        //toJson方法可以把java对象转换为json字符串
        String personJsonString = gson.toJson(person);
        System.out.println(personJsonString);

        //fromJson把json字符串转换回java对象
        //第一个参数是json字符串
        //第二个参数是转换回去的java对象类型
        Person person1 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person1);
    }

    //1.2.2 List和json的转换
    @Test
    public void test2(){
        List<Person> personList=new ArrayList<>();
        personList.add(new Person(1,"国哥"));
        personList.add(new Person(1,"康师傅"));

        Gson gson=new Gson();
        //把List转换为json字符串
        String personListJsonString = gson.toJson(personList);
        System.out.println(personListJsonString);

        List<Person> list = gson.fromJson(personListJsonString,new PersonListType().getType());
        System.out.println(list);
        Person person = list.get(0);
        System.out.println(person);
    }

    //1.2.3 map和json的转换
    @Test
    public void test3(){
        Map<Integer,Person> personMap=new HashMap<>();
        personMap.put(1,new Person(1,"国哥好帅"));
        personMap.put(2,new Person(2,"康师傅也好帅"));

        Gson gson=new Gson();
        //把map集合转化为json字符串
        String personMaoJsonString = gson.toJson(personMap);
        System.out.println(personMaoJsonString);

//         Map<Integer,Person> personMap2= gson.fromJson(personMaoJsonString, new PersonMapType().getType());
        Map<Integer,Person> personMap2= gson.fromJson(personMaoJsonString, new TypeToken<HashMap<Integer,Person>>(){}.getType());
        System.out.println(personMap2);
        Person p=personMap2.get(1);
        System.out.println(p);

    }

}
